package com.czm.art_light.interceptor;

import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.constant.SystemConfigConsts;
import com.czm.art_light.entity.ArtUser;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.mapper.ArtUserMapper;
import com.czm.art_light.util.JwtUtils;
import com.czm.art_light.util.UserHolderUtility;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * Token 解析拦截器
 */
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private ArtUserMapper artUserMapper;

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler) throws Exception {
        // 获取登录 JWT
        String token = request.getHeader(SystemConfigConsts.HTTP_AUTH_HEADER_NAME);
        if (!StringUtils.hasText(token) || "null".equals(token)) {
            // token 为空
            throw new BusinessException(ArtErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        Integer userId = JwtUtils.parseToken(token, SystemConfigConsts.FRONT_WX_LOGIN_FLAG);
        if (Objects.isNull(userId)) {
            // token 解析失败
            throw new BusinessException(ArtErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        ArtUser artUser = artUserMapper.getById(userId);
        if (Objects.isNull(artUser)) {
            // 用户不存在
            throw new BusinessException(ArtErrorCodeEnum.USER_ACCOUNT_NOT_EXIST);
        }
        // 设置 userId 到当前线程
        UserHolderUtility.setUserId(userId);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * DispatcherServlet 完全处理完请求后调用，出现异常照常调用
     */
    @SuppressWarnings("NullableProblems")
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        // 清理当前线程保存的用户数据
        UserHolderUtility.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
